package com.lancoo.answer.ui.ques.quesBody;

import android.os.Bundle;
import android.text.TextUtils;
import android.util.Log;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.FrameLayout;

import androidx.annotation.NonNull;
import androidx.annotation.Nullable;
import androidx.fragment.app.Fragment;

import com.lancoo.answer.R;
import com.lancoo.answer.component.InteractWebView;
import com.lancoo.answer.model.AnswerConstant;
import com.lancoo.answer.model.ConstantBean;
import com.lancoo.answer.model.TaskState;
import com.lancoo.answer.model.bean.Child;
import com.lancoo.answer.model.bean.Item;
import com.lancoo.answer.model.bean.Ques;
import com.lancoo.answer.model.bean.Type;
import com.lancoo.answer.ui.ques.SpliteLayoutFragment;
import com.rxjava.rxlife.RxLife;

import org.jetbrains.annotations.NotNull;

import java.util.List;
import java.util.concurrent.TimeUnit;
import java.util.regex.Matcher;
import java.util.regex.Pattern;

import io.reactivex.Single;
import io.reactivex.android.schedulers.AndroidSchedulers;
import io.reactivex.schedulers.Schedulers;

/**
 * Created by pengmi on 2021/12/16 9:30
 * Description:复合写作题干加载fragment
 */
public class CompoundWritingQuesBodyFragment extends Fragment {

    private static final String TAG = "CompoundWritingQuesBody";

    private FrameLayout frameLayout;
    private InteractWebView interactWebView;
    private Ques ques;
    private String currentItemSortIndex = "";
    private int defaultLoadIndex = -1;

    public static Fragment loadQueseFragment(int typeIndex, int queseIndex, int childIndex, int defaultIndex) {
        Log.e("eee", "loadQueseFragment anInt:" + defaultIndex);
        CompoundWritingQuesBodyFragment queseFragment = new CompoundWritingQuesBodyFragment();
        Bundle mBundle = new Bundle();
        mBundle.putInt(AnswerConstant.KEY_TYPEINDEX, typeIndex);
        mBundle.putInt(AnswerConstant.KEY_QUESINDEX, queseIndex);
        mBundle.putInt(AnswerConstant.KEY_CHILDINDEX, childIndex);
        mBundle.putInt(AnswerConstant.KEY_LOADCHILDINDEX, defaultIndex);
        queseFragment.setArguments(mBundle);
        return queseFragment;
    }

    @Nullable
    @Override
    public View onCreateView(@NonNull LayoutInflater inflater, @Nullable ViewGroup container, @Nullable Bundle savedInstanceState) {
        return inflater.inflate(R.layout.ev_fragment_ques_body, container, false);
    }

    @Override
    public void onViewCreated(@NonNull View view, @Nullable Bundle savedInstanceState) {
        super.onViewCreated(view, savedInstanceState);
        if (getArguments() == null || getContext() == null || getActivity() == null) {
            return;
        }
        if (ConstantBean.Companion.getConstantExamBean() == null) {
            return;
        }
        List<Type> kindBeanListk = ConstantBean.Companion.getConstantExamBean().getTypeList();
        if (kindBeanListk == null) {
            return;
        }
        int typeIndex = getArguments().getInt(AnswerConstant.KEY_TYPEINDEX);
        int quesIndex = getArguments().getInt(AnswerConstant.KEY_QUESINDEX);
        int childIndex = getArguments().getInt(AnswerConstant.KEY_CHILDINDEX);
        if (kindBeanListk.get(typeIndex) == null ||
                kindBeanListk.get(typeIndex).getQuesList() == null) {
            return;
        }

        ques = kindBeanListk.get(typeIndex).getQuesList().get(quesIndex);
        interactWebView = new InteractWebView(getContext());
        if (ques == null || ques.getQuesBody() == null) {
            return;
        }
        frameLayout = view.findViewById(R.id.framelayout);
        frameLayout.addView(interactWebView);
        String quesBody = ques.getQuesBody();//大题题干
        Boolean isIndentation = ques.getIsIndentQuesBody();
        StringBuffer stringBuffer = new StringBuffer();
        stringBuffer.append(quesBody);
        for (Child child : ques.getChildList()) {
            stringBuffer.append("<br>");
            stringBuffer.append(child.getChildAsk());
        }
        if (ConstantBean.getTaskState() == TaskState.ORIGINAL) {
            interactWebView.showOrHideAnalysisButton(0);
        } else {
            interactWebView.showOrHideAnalysisButton(1);
        }
        interactWebView.setQues(ques);
        interactWebView.setIsIndentation(isIndentation);
        if (defaultLoadIndex == -1) {
            defaultLoadIndex = getArguments().getInt(AnswerConstant.KEY_LOADCHILDINDEX);
        }
        Log.e("0713", ques.getTypeName() + "默认加载下标:" + defaultLoadIndex);
        interactWebView.initWebView(getActivity(), stringBuffer.toString(), new InteractWebView.Callback() {
            @Override
            public void clickCallback(@NotNull String position) {
                Log.e(TAG, "clickCallback position:" + position);
                wvLoadUrl(position);
                getRealIndex(position);
            }

            @Override
            public void finishCallback() {
                String itemSortIndex = "underline" + ques.getChildList().get(childIndex).getItemList().get(0).getItemSortIndex();
                wvLoadUrl(itemSortIndex);
            }
        });
    }

    private void wvLoadUrl(String position) {
        if (TextUtils.equals(currentItemSortIndex, position)) {
            return;
        }
        if (interactWebView == null) {
            return;
        }
        currentItemSortIndex = position;
        Log.e(TAG, "wvLoadUrl:" + position);
        interactWebView.scrollPosition(position);
        if (ques.getGenreID().equals("78")) { //复合写作
            interactWebView.scrollTranslatePosition(position);
            for (Child it : ques.getChildList()) {
                String itemSortIndex = "underline" + it.getItemList().get(0).getItemSortIndex();
                if (position.equals(itemSortIndex)) {
                    interactWebView.loadTranslateUrl(position, true);
                } else {
                    interactWebView.loadTranslateUrl(itemSortIndex, false);
                }
            }
        } else {
            for (Child it : ques.getChildList()) {
                if (ConstantBean.getTaskState() == TaskState.ORIGINAL) {
                    interactWebView.loadOriginUrl(it.getItemList().get(0),
                            position.equals(it.getItemList().get(0).getItemSortIndex()),
                            true);
                } else {
                    interactWebView.loadUrl(it.getItemList().get(0),
                            position.equals(it.getItemList().get(0).getItemSortIndex()),
                            false,
                            true);
                }
            }
        }
    }

    public String getPosition(String args) {
        String regEx = "[^0-9]";
        Pattern p = Pattern.compile(regEx);
        Matcher m = p.matcher(args);
        return m.replaceAll("").trim();
    }

    @Override
    public void onDestroyView() {
        super.onDestroyView();
        if (interactWebView != null) {
            interactWebView.release();
        }
        if (frameLayout != null) {
            frameLayout.removeAllViews();
        }
    }

    public void loadItemIndex(int childIndex) {
        Log.e("0713", ques.getTypeName() + "loadItemIndex:" + childIndex);
        if (ConstantBean.getTaskState() != TaskState.TRAINING &&
                ques != null && ques.getChildList() != null && ques.getChildList().size() > 0) {

            String typeNo = ques.getTypeNo();
            if (TextUtils.isEmpty(typeNo)) {
                return;
            }
            if (TextUtils.equals(typeNo, "H") || TextUtils.equals(typeNo, "D")
                    || TextUtils.equals(typeNo, "X") || TextUtils.equals(typeNo, "k")
                    || TextUtils.equals(typeNo, "P")) {
                return;
            }
            List<Child> childList = ques.getChildList();
            if (childIndex < childList.size() && childIndex >= 0) {
                if (childList.get(childIndex).getItemList() != null &&
                        childList.get(childIndex).getItemList().size() > 0) {
                    wvLoadUrl("underline" + childList.get(childIndex).getItemList().get(0).getItemSortIndex());
                }
            }
        }
    }

    private void getRealIndex(String position) {

        if (ques == null || ques.getChildList() == null) {
            return;
        }
        int childIndex = 0;
        for (Child child : ques.getChildList()) {
            List<Item> itemList = child.getItemList();
            if (itemList == null) {
                continue;
            }
            if (TextUtils.equals(position, "underline" + itemList.get(0).getItemSortIndex())) {
                break;
            }
            childIndex++;
        }
        Log.e(TAG, "getRealIndex" + childIndex);
        final int choiseIndex = childIndex;
        Single.timer(0, TimeUnit.MILLISECONDS).subscribeOn(Schedulers.io())
                .observeOn(AndroidSchedulers.mainThread())
                .as(RxLife.as(this))
                .subscribe(aLong -> {
                    if (getParentFragment() instanceof SpliteLayoutFragment) {
                        SpliteLayoutFragment spliteLayoutFragment = ((SpliteLayoutFragment) getParentFragment());
                        spliteLayoutFragment.jumpToAimChildFragment(choiseIndex, 0, 3);
                    }
                });
    }

    void switchChildAsk(int position) {
        String switchSortIndex = ques.getChildList().get(position).getItemList().get(0).getItemSortIndex();
        interactWebView.scrollTranslatePosition("underline" + switchSortIndex);
        for (Child it : ques.getChildList()) {
            String itemSortIndex = it.getItemList().get(0).getItemSortIndex();
            if (switchSortIndex.equals(itemSortIndex)) {
                interactWebView.loadTranslateUrl("underline" + switchSortIndex, true);
            } else {
                interactWebView.loadTranslateUrl("underline" + itemSortIndex, false);
            }
        }
    }


    public void onClickItemIndex(int position) {
        defaultLoadIndex = position;
        if (ques == null) {
            return;
        }
        switchChildAsk(position);
    }

    public void adjustFontSize(){
        if(interactWebView!=null){
            interactWebView.setFontSize();
        }
    }

}